package net.quindu.android.smsfilter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class FilterActivity extends Activity {
	public final static int SUCCESS_RETURN_CODE = 1;
	public final static int SUB_ACTIVITY_CONDITIONS = 1;
	
	SQLiteDatabase db;
	int filterId = -1;
	EditText editTextFilterName;
	ArrayAdapter<MenuElement>  conditionsList;
	ArrayAdapter<MenuElement>  actionsList;
	
	ListView conditionsView;
	ListView actionsView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.filter);
		
        DatabaseHelper dbHelper = new DatabaseHelper(this);
        db = dbHelper.getReadableDatabase();	
        
		
		Bundle filterIdBundle = getIntent().getExtras();

		String filterName = "";
		if(filterIdBundle == null){         
	        ContentValues initialValues = new ContentValues();
	        initialValues.put("title", "New Filter");        
	        db.insert("sms_filter", null, initialValues);
	        
	        Cursor lastIdCursor = db.rawQuery("SELECT last_insert_rowid() AS lastInsertId", null);
	        lastIdCursor.moveToNext();
	        filterId = lastIdCursor.getInt(0);
	        filterName = "New Filter " + filterId;	        
	        db.rawQuery("UPDATE sms_filter SET title = '" + filterName + "' WHERE filter_id=" + filterId + "", null);
		}else{
			filterId = filterIdBundle.getInt("id");			
	        Cursor cursor = db.rawQuery("SELECT title FROM sms_filter WHERE filter_id=" + filterId + "", null);
	        cursor.moveToNext();
	        filterName = cursor.getString(0);	        			
		}
        
		editTextFilterName =  (EditText) findViewById(R.id.EditTextFilterName);
		editTextFilterName.setText(filterName);
		editTextFilterName.selectAll();
		

		
		//------ conditions
		
		Button button = (Button) findViewById(R.id.ButtonConditionAdd);
		button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(FilterActivity.this,FilterConditionActivity.class);
				Bundle bundle = new Bundle();
				bundle.putInt("filter_id", (int) filterId);	
				i.putExtras(bundle);
				startActivityForResult(i, SmsFilter.SUB_ACTIVITY_FILTER_DETAIL);
			}
		});		
		
		conditionsView = (ListView) findViewById(R.id.ListViewConditions);
        conditionsList = new ArrayAdapter<MenuElement>(this, android.R.layout.simple_list_item_1);
        conditionsView.setAdapter(conditionsList);
        populateConditionsListItems();	        
        conditionsView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {						
				Intent i = new Intent(FilterActivity.this,FilterConditionActivity.class);
				Bundle bundle = new Bundle();
				bundle.putInt("filter_id", (int) filterId);	
				bundle.putInt("id", (int) conditionsList.getItem(position).getId());
				i.putExtras(bundle);
				startActivityForResult(i, SmsFilter.SUB_ACTIVITY_FILTER_DETAIL);				
			}
          });        
        
		//------ actions
        
		Button buttonAct = (Button) findViewById(R.id.ButtonActionAdd);
		buttonAct.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(FilterActivity.this,FilterActionActivity.class);
				Bundle bundle = new Bundle();
				bundle.putInt("filter_id", (int) filterId);	
				i.putExtras(bundle);
				startActivityForResult(i, SmsFilter.SUB_ACTIVITY_FILTER_DETAIL);
			}
		});        
		
		actionsView = (ListView) findViewById(R.id.ListViewActions);
        actionsList = new ArrayAdapter<MenuElement>(this, android.R.layout.simple_list_item_1);
        actionsView.setAdapter(actionsList);
        populateActionsListItems();	        
        actionsView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {						
				Intent i = new Intent(FilterActivity.this,FilterActionActivity.class);
				Bundle bundle = new Bundle();
				bundle.putInt("filter_id", (int) filterId);	
				bundle.putInt("id", (int) actionsList.getItem(position).getId());
				i.putExtras(bundle);
				startActivityForResult(i, SmsFilter.SUB_ACTIVITY_FILTER_DETAIL);				
			}
          });   
        
        Button deleteButton = (Button) findViewById(R.id.ButtonActionDelete);
		deleteButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				  delete();
			}
		});        
        
	}
	
	private void populateConditionsListItems(){
        Cursor cursor = db.query("sms_condition", new String[] {"_id" , "type_id", "val"}, null , null, null, null, null);
    	conditionsList.clear();
        while(cursor.moveToNext()){
        	String title = "";
        	switch(cursor.getInt(1)){
	        	case(1):
	        		title += this.getString(R.string.condition_type_sender);
	        	break;
	        	case(2):
	        		title += this.getString(R.string.condition_type_text);
	        	break;
	        	case(3):
	        		title += this.getString(R.string.condition_type_regex);
	        	break;	        	
        	}
        	title += " : " + cursor.getString(2);
        	
        	
        	conditionsList.add(new MenuElement(title, cursor.getInt(0)));        	
        }
        
        conditionsList.notifyDataSetChanged();               
	}		
	
	private void populateActionsListItems(){
        Cursor cursor = db.query("sms_action", new String[] {"_id" , "type_id", "val"}, null , null, null, null, null);
        actionsList.clear();
        while(cursor.moveToNext()){
        	String title = "";
        	switch(cursor.getInt(1)){
	        	case(1):
	        		title += this.getString(R.string.action_type_ring);
	        	break;
	        	case(2):
	        		title += this.getString(R.string.action_type_vibrate);
	        	break;
	        	case(3):
	        		title += this.getString(R.string.action_type_ring_prevent);
	        	break;
	        	case(4):
	        		title += this.getString(R.string.action_type_vibrate_prevent);
	        	break;		      
	        	
	        	case(5):
	        		title += this.getString(R.string.action_type_popup);
	        	break;
	        	case(6):
	        		title += this.getString(R.string.action_type_delete_older);
	        	break;
	        	case(7):
	        		title += this.getString(R.string.action_type_delete);
	        	break;		 	        	
        	
        	}
        	
        	
        	actionsList.add(new MenuElement(title, cursor.getInt(0)));        	
        }
        
        actionsList.notifyDataSetChanged();               
	}		
	
	public void saveValues(){
        ContentValues initialValues = new ContentValues();
        initialValues.put("title", editTextFilterName.getText().toString()); 		  
        db.update("sms_filter", initialValues, "filter_id = " + filterId, null);		
	}
	
	@Override
	public void onBackPressed() {
		saveValues();
		super.onBackPressed();
	}	
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);				 	
		populateConditionsListItems();
		populateActionsListItems();
	}		
	
	@Override
	public void onStop() {
          setResult(RESULT_OK, null);
		  super.onStop();
		}	
	
	public void delete(){
		db.delete("sms_action", "filter_id = " + filterId, null);
		db.delete("sms_condition", "filter_id = " + filterId, null);
		db.delete("sms_filter", "filter_id = " + filterId, null);
		
		finish();
		
	}	
	
}